#!/bin/bash

#ENV
basepath=$(cd `dirname $0`; pwd)
echo "base path:${basepath}"
workpath=${1:-${basepath}}
echo "workspace: ${workpath}"

artifactsDir="${workpath}/artifacts"
artifactsUiDir="${artifactsDir}/webui"
artifactsUiFileName=$(ls ${artifactsUiDir} -ltr |tail -1|awk '{print $NF}')
uizip="${artifactsUiDir}/${artifactsUiFileName}"

workDir="${workpath}/work"
webuipath="${workDir}/webui"
#unzip ui.zip
echo "uizip file ${uizip}"
if [ -f "${uizip}" ]
then
	#clean webui
	echo "clean web ui ${webuipath}"
	rm -rf ${webuipath}
        echo "unzip ui file ${uizip}"
        unzip  -q -d ${webuipath} ${uizip}
fi

#stop running containers
echo "stop running containers..."
docker stop `docker ps -a | grep 'cus_ui' | awk '{print $1}'`
#remove containers
echo "remove containers"
docker rm `docker ps -a | grep 'cus_ui' | awk '{print $1}'`

#start container
count=${2:-2}
index=0
while(( $index < $count ))
do
        port=`expr 9190 + $index`
        name="cus_ui${index}"
        echo "start container ${name} on port: ${port}"
        docker run -idt --name ${name} --link cus.api:cus.api -e TZ="Asia/Shanghai" -v /etc/localtime:/etc/localtime -v ${webuipath}:/var/www/html -p ${port}:8006 node:ex supervisor -w public,routes,views -e lang,html,js,css,json app.js
        let "index++"
done
